package com.zhuhjay.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhuhjay.annotation.ApiLimiter;
import com.zhuhjay.annotation.RecordLog;
import com.zhuhjay.config.SystemConfig;
import com.zhuhjay.enums.HttpCode;
import com.zhuhjay.model.dto.UserRegisterDto;
import com.zhuhjay.model.dto.UserUpdateDto;
import com.zhuhjay.model.entity.SystemUser;
import com.zhuhjay.model.vo.UserInfoVo;
import com.zhuhjay.service.SystemUserService;
import com.zhuhjay.utils.FileUtils;
import com.zhuhjay.utils.SecurityContextHolder;
import com.zhuhjay.utils.result.Result;
import com.zhuhjay.utils.result.ResultBean;
import com.zhuhjay.utils.result.ResultMap;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.zhuhjay.config.SystemConfig.AVATAR_DIR;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Zhuhjay
 * @since 2023-01-11
 */
@Api(tags = "系统用户控制器")
@RestController
@RequestMapping("/user")
public class SystemUserController {

    @Resource
    private SystemUserService userService;

    @Resource
    private SystemConfig systemConfig;

    @ApiOperation("用户注册")
    @PostMapping("register")
    public Result register(@RequestBody @Valid UserRegisterDto userRegister) {
        return userService.register(userRegister);
    }

    @ApiOperation("获取用户信息")
    @GetMapping({"/", "{userId}"})
    public Result userInfo(@PathVariable(required = false) Long userId) {
        // 每次获取都是获取最新的用户数据
        userId = userId == null ? SecurityContextHolder.getLoginUserDetail().getId() : userId;
        SystemUser user = userService.getById(userId);
        UserInfoVo userInfo = new UserInfoVo();
        // 进行数据脱敏(屏蔽不必要的数据)
        BeanUtil.copyProperties(user, userInfo);
        return ResultBean.ok().data(userInfo);
    }

    @ApiOperation("分页查询用户")
    @GetMapping("page/{pageNum}/{pageSize}")
    public Result page(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
        Page<SystemUser> page = new Page<>(pageNum, pageSize);
        return ResultMap.ok().beanToData(
                userService.lambdaQuery().select(
                                SystemUser::getId,
                                SystemUser::getUsername,
                                SystemUser::getNickName,
                                SystemUser::getAvatar,
                                SystemUser::getEmail,
                                SystemUser::getTelephone,
                                SystemUser::getStatus,
                                SystemUser::getCreateTime)
                        .page(page), "total", "current", "size", "records");
    }

    @ApiOperation("更新用户信息")
    @PutMapping
    public Result update(@RequestBody @Valid UserUpdateDto userUpdateDto) {
        // 获取登录用户的id
        int userId = SecurityContextHolder.getLoginUserDetail().getId();
        SystemUser user = new SystemUser();
        BeanUtil.copyProperties(userUpdateDto, user);
        user.setId(userId);
        userService.updateById(user);
        return ResultBean.ok(HttpCode.UPDATE_SUCCESS);
    }

    @ApiOperation("更新用户头像")
    @PostMapping("avatar")
    public Result updateAvatar(@RequestPart MultipartFile file) {
        FileUtils.checkFileIsImage(file);
        final String dirPath = systemConfig.getAvatarPath();
        // 创建存放头像的文件夹，如果不存在
        File avatar = FileUtil.mkdir(dirPath);
        // 生成文件名
        String fileName = FileUtils.generateFileName(file.getOriginalFilename());
        try {
            FileUtil.writeBytes(file.getBytes(), avatar + File.separator + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultBean.fail("头像上传失败");
        }
        // 获取当前登录用户，更新头像
        SystemUser user = new SystemUser();
        user.setId(SecurityContextHolder.getLoginUserDetail().getId());
        user.setAvatar(AVATAR_DIR + "/" + fileName);
        userService.updateById(user);
        return ResultBean.ok(HttpCode.UPDATE_SUCCESS);
    }

    @ApiOperation("测试方法")
    @ApiLimiter(limit = 5, expire = 15)
    @RecordLog("测试方法")
    @GetMapping("test")
    public Result test(Integer div) {
        try {
            TimeUnit.MILLISECONDS.sleep(110);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        int i = 1 / div;
        return ResultBean.ok();
    }

}
